package caronas.infra;

import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.resource.ResourceMethod;
import caronas.controller.UsuarioController;
import caronas.modelo.UsuarioWeb;

@Intercepts
@RequestScoped
public class LoginInterceptor implements Interceptor {

    private Result result;
    private UsuarioWeb usuarioWeb;
    private HttpServletRequest request;
    public LoginInterceptor(Result result, UsuarioWeb usuarioWeb, HttpServletRequest request) {
        this.result = result;
        this.usuarioWeb = usuarioWeb;
        this.request = request;
    }
    
    /**
     * @param method m�todo que define quais m�todos dos controladores dever�o ser interceptados.
     * Intercepta todos os m�todos que n�o estejam com a anota��o @LoginBypass
     */
    public boolean accepts(ResourceMethod method) {
        return
            !(method.getMethod().isAnnotationPresent(LoginBypass.class) ||
            method.getResource().getType().isAnnotationPresent(LoginBypass.class));
    }

    public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) {
    	String uri;
        if (usuarioWeb.isLogado()) {
            stack.next(method, resourceInstance);
        } else {
            result.redirectTo(UsuarioController.class).loginForm();
            uri = request.getRequestURI();
            uri = uri.replaceFirst(request.getContextPath(), "");  
            request.getSession().setAttribute("called_uri", uri);  
        }
    }

}